﻿using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Enums;
using DeviceCommons.DeviceMessages.Models.V1;
using System.Buffers;

namespace DeviceCommons.DeviceMessages.Serialization.V2.Serializers
{
    public class DeviceMessageInfoReadingStateSerializer : AbstractMessageSerializer<IDeviceMessageInfoReadingState>, IDeviceMessageInfoReadingStateSerializer
    {
        public DeviceMessageInfoReadingStateSerializer() : base(new DeviceMessageInfoReadingState())
        {

        }

        public override void Serializer(ArrayBufferWriter<byte> writer, IDeviceMessageInfoReadingState message)
        {
            ArgumentNullException.ThrowIfNull(message);
            ArgumentNullException.ThrowIfNull(message.SID);
            ArgumentNullException.ThrowIfNull(message.ValueType);
            ArgumentNullException.ThrowIfNull(message.Value);
            writer.Write([message.SID]);
            writer.Write([message.Type]);
            if (message.ValueType == StateValueTypeEnum.String)
            {
                if (message.Value.Length > byte.MaxValue) throw new IndexOutOfRangeException(nameof(message.Value));
                writer.Write([(byte)message.Value.Length]);
            }
            else if (message.ValueType == StateValueTypeEnum.Binary)
            {
                if (message.Value.Length > ushort.MaxValue) throw new IndexOutOfRangeException(nameof(message.Value));
                writer.Write(BitConverter.GetBytes((UInt16)message.Value.Length));
            }
            writer.Write(message.Value);
        }
    }
}
